﻿var Settings = {
    dateFormat: 'dd/MM/yyyy',
    Calendar: {
        calendarFormat: 'dd/MM/yyyy',
        intMaxDate: null,
        intMinDate: null,
        isEnabled: true,
        strFrom: "From",
        strTo: "To"
    }
};

function PressreleasesObject(sourceCode, sourceId) {
    this.search = null;
    this.calendar = new CalendarObject();

    var startCal = null,
        endCal = null,
        lastRequestParams = null,
        ajaxWorking = undefined,
        loader = null,
        page = null,
        pagePhoto = null,
        pageVideo = null,
        dateFrom = null,
		dateTo = null,
        intCurrentNewsOnPage = 1,
        intCurrentPageItemFrom = 0,
        intCurrentPageItemTo = 0,
        intPressReleasesOnPage = 15,
        strPrevious = 'Previous',
        strNext = 'Next',
        totalContainer = null,
        timer = null,
        News = [],
        strAttachmentLocationURL = '',
        me = this;

    var getRequestParameters = function () {
        return {
            sourceCode: sourceCode,
            langId: 32,
            sourceId: sourceId,
            searchPharse: null,
            fromDate: null,
            toDate: null,
            pageIndex: 0,
            pageJummp: 0
        };
    };

    var initialize = function () {
        if (!loader)
            loader = new LoaderObject();
        if (!totalContainer)
            totalContainer = new TotalContainerObject();
        ToolContainer.load();

        if (me.calendar) {
            me.calendar.dateFormat = Settings.Calendar.calendarFormat;
            me.calendar.strFrom = Settings.Calendar.strFrom;
            me.calendar.strTo = Settings.Calendar.strTo;
            me.calendar.isEnabled = Settings.Calendar.isEnabled;
            me.calendar.intMaxDate = Settings.Calendar.intMaxDate;
            me.calendar.intMinDate = Settings.Calendar.intMinDate;
            //calendar.selectRange = selectRange;
            me.calendar.load();
        }
    };

    this.loadFinanceReport = function () {
        initialize();
        var main = $('#PressReleases'),
            i,
            item;

        page = new PagesObject($('#PagesContainer'));
        page.clickedCall = function () { me.getPressreleases(false, false, false, page) };
        intCurrentNewsOnPage = intPressReleasesOnPage;

        this.search = new SearchObject();
        this.search.searchCall = function () {
            var obj = me.calendar.getCurrentDates();
            dateFrom = obj.dFrom;
            dateTo = obj.dTo;

            enableAllTab(true, page);
        };
        this.search.searchRemoveCall = function () {
            $('#Tabs a#InsidersSelector').removeClass('display-none');
            $('#Tabs a#ByTypeSelector').removeClass('display-none');
            //This.loadYearsData(This.Calendars.getMaxDate().getFullYear());
        };

        for (i = 0; i < intPressReleasesOnPage; i++) {
            item = new PressReleaseItemObejct('PressRelease_' + i, me);
            main.append(item.root);
            item.load();

            item.root.addClass('PressRelease' + (i % 2 == 0 ? 'Odd' : 'Even'))

            News.push(item);
        }
        me.getPressreleases(true, false, false, page);
    };

    function enableAllTab(setPeriodText, pagingObject) {
        /*
            Enables the All Tab
        */
        $('#Tabs a').removeClass('selected');
        $('#Tabs a#AllSelector').addClass('selected');

        Utility.blur();

        //This.Types.remove();
        intCurrentNewsOnPage = intPressReleasesOnPage;

        if (setPeriodText)
            me.getPressreleases(true, false, true, pagingObject);
        else
            me.getPressreleases(true, true, false, pagingObject);
    }

    this.loadPhoto = function () {
        initialize();
        var main = $('#PhotoReleases'),
            i,
            item;

        pagePhoto = new PagesObject($('#PagesPhotoContainer'));
        pagePhoto.clickedCall = function () { me.getPressreleases(false, false, false, pagePhoto) };
        intCurrentNewsOnPage = intPressReleasesOnPage;

        for (i = 0; i < intPressReleasesOnPage; i++) {
            item = new PressReleaseItemObejct('PhotoRelease_' + i, me);
            main.append(item.root);
            item.load();

            item.root.addClass('PhotoRelease PhotoRelease' + (i % 2 == 0 ? 'Odd' : 'Even'))

            News.push(item);
        }
        me.getPressreleases(true, false, false, pagePhoto);
    }

    this.loadVideo = function () {
        initialize();
        var main = $('#VideoReleases'),
            i,
            item;

        pageVideo = new PagesObject($('#PagesVideoContainer'));
        pageVideo.clickedCall = function () { me.getPressreleases(false, false, false, pageVideo) };
        intCurrentNewsOnPage = intPressReleasesOnPage;

        for (i = 0; i < intPressReleasesOnPage; i++) {
            item = new PressReleaseItemObejct('VideoRelease_' + i, me);
            main.append(item.root);
            item.load();

            item.root.addClass('VideoRelease VideoRelease' + (i % 2 == 0 ? 'Odd' : 'Even'))

            News.push(item);
        }
        me.getPressreleases(true, false, false, pageVideo);
    }

    this.getPressreleases = function (isPage, isPartialPageLoad, setPeriodText, pagingObject) {
        if (typeof isPage != 'boolean')
            isPage = false;
        if (typeof isPartialPageLoad != 'boolean')
            isPartialPageLoad = false;
        if (typeof setPeriodText != 'boolean')
            setPeriodText = false;

        if (typeof timer == 'number')
            clearTimeout(timer);

        if (isPage) {
            pagingObject.selectedPageIndex = 0;
            pagingObject.hide(true);
        }

        var index = News.length;

        if (isPage && isPartialPageLoad || !isPage) {
            while (index--) {
                News[index].hide();
            }
        } else {
            while (index--) {
                News[index].remove();
            }
        }

        var requestUrl = baseUri + 'Home/GetPressreleases';
        $.ajaxSetup({ cache: false });
        var s0 = new Date();

        var s1 = dateFrom;
        if (s1 != null) {
            s1 = new Date(s1.getFullYear(), s1.getMonth(), s1.getDate(), 0, 0, 0, 0);
            s1 = s1.toJSON();
        }
        var s2 = dateTo;
        if (s2 != null) {
            s2 = new Date(s2.getFullYear(), s2.getMonth(), s2.getDate(), 0, 0, 0, 0);
            s2 = s2.toJSON();
        }
        var s3 = $('#SearchBox').val();
        if (s3 == 'Keyword')
            s3 = '';
        var pageParams = { pageIndex: pagingObject.selectedPageIndex, pageJummp: intCurrentNewsOnPage, searchPhrase: s3, fromDate: s1, toDate: s2 };
        var parameters = getRequestParameters();
        parameters = $.extend({}, parameters, pageParams);

        //Check ajax working
        if (ajaxWorking != undefined) {
            ajaxWorking.abort();
        }
        // get data
        ajaxWorking = $.ajax({
            url: requestUrl,
            dataType: 'json',
            type: 'POST',
            data: parameters,
            beforeSend: function () {
                loader.show();
            },
            complete: function () {
                loader.hide();
            },
            success: function (data) {
                if ($.isObject(data)) {
                    var length = data.Data.length,
                        totalRow = data.TotalRow,
                        attachments = data.DataAttachment;
                    if (me.search != null)
                        me.search.Error.hide();
                    totalContainer.show(totalRow);
                    if (isPage)
                        pagingObject.setPages(totalRow, intCurrentNewsOnPage, isPartialPageLoad);
                    addPressReleases(data.Data, isPage && !isPartialPageLoad, attachments);
                }
            },
            error: function () {
                if (me.search != null)
                    me.search.Error.hide();
                loader.hide();
            }
        });
    }

    this.closeAllMessages = function () {
        var index = News.length;
        while (index--) {
            News[index].closeQuickMessage();
        }
    }

    var addPressReleases = function (newsArr, clearOldNews, attachmentsArr) {

        var i, length = newsArr.length < intCurrentNewsOnPage ? newsArr.length : intCurrentNewsOnPage, obj;

        for (i = 0; i < News.length; i++) {
            if (i < length) {
                News[i].set(newsArr[i], clearOldNews, attachmentsArr);
            } else {
                News[i].remove();
            }
        }
    }
};


$(document).ready(function () {
    var newsObject,
        videoObject,
        photoObject;
    function changeTab(role, sourceCode) {
        //Change active tab style to latest-trades tab (default tab)
        $('.Tabs-Tab-Container').removeClass('selected');
        $('.Tabs-Tab-Container').filter('[role="' + role + '"]').addClass('selected');
        if (role == 'FinanceReport') {
            $('#PageVideoContainer').addClass('display-none');
            $('#PagePhotoContainer').addClass('display-none');
            $('#PageFlickContainer').removeClass('display-none');
            //Load data  
            if (!newsObject) {
                newsObject = new PressreleasesObject('FinanceReport', 12);
                newsObject.loadFinanceReport();
            }

        } else if (role == 'SocialNetwork-Video') {
            $('#PageVideoContainer').removeClass('display-none');
            $('#PagePhotoContainer').addClass('display-none');
            $('#PageFlickContainer').addClass('display-none');
            //
            if (!videoObject) {
                videoObject = new PressreleasesObject('SocialNetwork', 3);
                videoObject.loadVideo();
            }
        }
        else if (role == 'SocialNetwork-Photo') {
            $('#PagePhotoContainer').removeClass('display-none');
            $('#PageVideoContainer').addClass('display-none');
            $('#PageFlickContainer').addClass('display-none');
            //
            if (!photoObject) {
                photoObject = new PressreleasesObject('SocialNetwork', 14);
                photoObject.loadPhoto();
            }
        }
    };

    //Init tabs
    (function () {
        $('.Tabs a').click(function (e) {
            e.preventDefault();
            var $this = $(this),
                role = $this.attr('role'),
                sourceCode = $this.attr('sourcecode');

            if ($this.hasClass('.selected')) {
                //return;
            }
            $this.parent().siblings().children('a.selected').removeClass('selected');

            $this.addClass('selected');
            changeTab(role, sourceCode);
            return false;
        }).filter('.selected').first().each(function () {
            var $this = $(this),
                role = $this.attr('role'),
                sourceCode = $this.attr('sourcecode');
            changeTab(role, sourceCode);
        });
    })();

    /* Facebook Like */
    var fb_c = "0";

    $(function () {
        $("#fb").css("right", "0");
    });

    function facebook_like_box_render() {
        if (fb_c == "0") {
            $("#fb").animate({ right: "-8" }, 1000);
            $("#facebox-like-box").animate({ right: "0" }, 1000);

            fb_c = "1";
        }
        else {
            $("#fb").animate({ right: "-300" }, 1000);
            $("#facebox-like-box").animate({ right: "-292" }, 1000);
            fb_c = "0";
        }
    }
    $('#fb-plugin-button').unbind('click').bind('click', function () {
        facebook_like_box_render();
    })

    $('.scrollup').click(function () {
        $(document).scrollTop(0);
    });
});